<template>
  <div class="app-container">
    <!-- 精简的搜索条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="用户ID" clearable style="width: 120px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商编码" prop="supplierCode">
        <el-input v-model="queryParams.supplierCode" placeholder="供应商编码" clearable style="width: 160px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input v-model="queryParams.supplierName" placeholder="供应商名称" clearable style="width: 160px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商类型" prop="supplierType">
        <el-select v-model="queryParams.supplierType" placeholder="供应商类型" clearable style="width: 120px">
          <el-option label="个人" :value="1" />
          <el-option label="企业" :value="2" />
          <el-option label="自营" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="认证状态" prop="certificationStatus">
        <el-select v-model="queryParams.certificationStatus" placeholder="认证状态" clearable style="width: 120px">
          <el-option label="未认证" :value="0" />
          <el-option label="已认证" :value="1" />
          <el-option label="认证失败" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请状态" prop="applicationStatus">
        <el-select v-model="queryParams.applicationStatus" placeholder="申请状态" clearable style="width: 120px">
          <el-option label="待申请" :value="0" />
          <el-option label="申请中" :value="1" />
          <el-option label="申请通过" :value="2" />
          <el-option label="申请拒绝" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="审核状态" clearable style="width: 120px">
          <el-option label="待审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="已拒绝" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 120px">
          <el-option label="待激活" :value="0" />
          <el-option label="启用" :value="1" />
          <el-option label="冻结" :value="2" />
          <el-option label="注销" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson">
        <el-input v-model="queryParams.contactPerson" placeholder="联系人" clearable style="width: 120px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:suppliers:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:suppliers:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:suppliers:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:suppliers:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 优化的表格展示 -->
    <el-table 
      v-loading="loading" 
      :data="suppliersList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      size="small"
      class="common-table"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" align="center" prop="supplierId" width="80" />
      <el-table-column label="用户ID" align="center" prop="userId" width="80" />
      <el-table-column label="供应商编码" align="center" prop="supplierCode" width="140" show-overflow-tooltip />
      <el-table-column label="供应商名称" align="left" prop="supplierName" min-width="180" show-overflow-tooltip />
      <el-table-column label="类型" align="center" prop="supplierType" width="80">
        <template slot-scope="scope">
          <el-tag :type="getSupplierTypeColor(scope.row.supplierType)" size="mini">
            {{ getSupplierTypeText(scope.row.supplierType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="contactPerson" width="100" show-overflow-tooltip />
      <el-table-column label="联系电话" align="center" prop="contactPhone" width="120" />
      <el-table-column label="公司名称" align="left" prop="companyName" width="150" show-overflow-tooltip />
      <el-table-column label="营业执照" align="center" prop="businessLicenseImage" width="80">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.businessLicenseImage" :src="scope.row.businessLicenseImage" :width="40" :height="40"/>
          <span v-else style="color: #C0C4CC;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="认证状态" align="center" prop="certificationStatus" width="90">
        <template slot-scope="scope">
          <el-tag :type="getCertificationStatusColor(scope.row.certificationStatus)" size="mini">
            {{ getCertificationStatusText(scope.row.certificationStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" prop="applicationStatus" width="90">
        <template slot-scope="scope">
          <el-tag :type="getApplicationStatusColor(scope.row.applicationStatus)" size="mini">
            {{ getApplicationStatusText(scope.row.applicationStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus" width="90">
        <template slot-scope="scope">
          <el-tag :type="getAuditStatusColor(scope.row.auditStatus)" size="mini">
            {{ getAuditStatusText(scope.row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag :type="getStatusColor(scope.row.status)" size="mini">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="信用等级" align="center" prop="creditRating" width="80">
        <template slot-scope="scope">
          <el-tag :type="getCreditRatingColor(scope.row.creditRating)" size="mini">
            {{ scope.row.creditRating }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="平均评分" align="center" prop="avgRating" width="90">
        <template slot-scope="scope">
          <el-rate v-model="scope.row.avgRating" disabled show-score text-color="#ff9900" score-template="{value}" style="display: inline-block;" />
        </template>
      </el-table-column>
      <el-table-column label="佣金费率" align="center" prop="commissionRate" width="80">
        <template slot-scope="scope">
          <span style="color: #E6A23C;">{{ (scope.row.commissionRate * 100).toFixed(2) }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="保证金" align="center" prop="depositBalance" width="100">
        <template slot-scope="scope">
          <span style="color: #67C23A;">¥{{ scope.row.depositBalance }}</span>
        </template>
      </el-table-column>
      <el-table-column label="统计" align="center" width="100">
        <template slot-scope="scope">
          <div style="font-size: 12px; line-height: 1.2;">
            <div>订单: {{ scope.row.totalOrders || 0 }}</div>
            <div>产品: {{ scope.row.totalProducts || 0 }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:suppliers:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:suppliers:remove']"
            style="color: #F56C6C;"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 优化的添加或修改供应商对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基础信息 -->
          <el-tab-pane label="基础信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="供应商编码" prop="supplierCode">
                  <el-input v-model="form.supplierCode" placeholder="供应商编码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商名称" prop="supplierName">
                  <el-input v-model="form.supplierName" placeholder="供应商名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="关联用户" prop="userId">
                  <el-select v-model="form.userId" placeholder="选择关联用户" clearable filterable remote reserve-keyword 
                             :remote-method="getUserList" :loading="userLoading" style="width: 100%">
                    <el-option
                      v-for="user in userOptions"
                      :key="user.userId"
                      :label="`${user.userName} (${user.nickName})`"
                      :value="user.userId">
                      <span style="float: left">{{ user.userName }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ user.nickName }}</span>
                    </el-option>
                  </el-select>
                  <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                    选择要关联的系统用户
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商类型" prop="supplierType">
                  <el-select v-model="form.supplierType" placeholder="选择类型" style="width: 100%">
                    <el-option label="个人供应商" :value="1" />
                    <el-option label="企业供应商" :value="2" />
                    <el-option label="平台自营" :value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人" prop="contactPerson">
                  <el-input v-model="form.contactPerson" placeholder="联系人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="form.contactPhone" placeholder="联系电话" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系邮箱" prop="contactEmail">
                  <el-input v-model="form.contactEmail" placeholder="联系邮箱" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="联系地址" prop="contactAddress">
                  <el-input v-model="form.contactAddress" type="textarea" :rows="2" placeholder="联系地址" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 企业信息 -->
          <el-tab-pane label="企业信息" name="company">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="公司名称" prop="companyName">
                  <el-input v-model="form.companyName" placeholder="公司名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="营业执照号" prop="businessLicense">
                  <el-input v-model="form.businessLicense" placeholder="营业执照号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="税务登记号" prop="taxNumber">
                  <el-input v-model="form.taxNumber" placeholder="税务登记号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="法人代表" prop="legalPerson">
                  <el-input v-model="form.legalPerson" placeholder="法人代表" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input v-model="form.idCard" placeholder="身份证号" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="营业执照照片">
                  <image-upload v-model="form.businessLicenseImage"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="身份证照片" prop="idCardImages">
                  <div class="json-editor-container">
                    <div class="json-editor-header">
                      <span>身份证照片</span>
                      <el-button size="mini" type="primary" @click="updateSimpleIdCardForm">手动同步JSON</el-button>
                    </div>
                    <div class="id-card-simple-layout">
                      <el-row :gutter="20">
                        <!-- 身份证正面 -->
                        <el-col :span="12">
                          <div class="id-card-item">
                            <div class="id-card-title">身份证正面</div>
                            <image-upload v-model="form.idCardFront" :limit="1" @input="onIdCardFrontChange" @change="onIdCardFrontChange" />
                          </div>
                        </el-col>
                        <!-- 身份证背面 -->
                        <el-col :span="12">
                          <div class="id-card-item">
                            <div class="id-card-title">身份证背面</div>
                            <image-upload v-model="form.idCardBack" :limit="1" @input="onIdCardBackChange" @change="onIdCardBackChange" />
                          </div>
                        </el-col>
                      </el-row>
                    </div>
                    <div class="json-preview">
                      <el-collapse>
                        <el-collapse-item title="JSON预览 (实时)" name="id-card-preview">
                          <div style="margin-bottom: 10px;">
                            <el-tag type="info" size="small">当前JSON对象</el-tag>
                            <pre>{{ JSON.stringify(simpleIdCardObject, null, 2) }}</pre>
                          </div>
                          <div>
                            <el-tag type="success" size="small">表单字段值</el-tag>
                            <pre>{{ form.idCardImages || '(空)' }}</pre>
                          </div>
                        </el-collapse-item>
                      </el-collapse>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 服务信息 -->
          <el-tab-pane label="服务信息" name="service">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="服务区域" prop="serviceAreas">
                  <div class="json-editor-container">
                    <div class="json-editor-header">
                      <span>服务区域配置</span>
                      <el-button size="mini" type="primary" icon="el-icon-plus" @click="addServiceArea">添加区域</el-button>
                    </div>
                    <div class="features-list">
                      <el-tag
                        v-for="(area, index) in serviceAreasList"
                        :key="index"
                        closable
                        @close="removeServiceArea(index)"
                        style="margin-right: 8px; margin-bottom: 8px;"
                        size="medium"
                        type="warning"
                      >
                        {{ area }}
                      </el-tag>
                      <el-input
                        v-if="serviceAreaInputVisible"
                        v-model="serviceAreaInputValue"
                        ref="saveServiceAreaInput"
                        size="small"
                        style="width: 120px;"
                        @keyup.enter.native="handleServiceAreaInputConfirm"
                        @blur="handleServiceAreaInputConfirm"
                      />
                      <el-button v-else size="small" @click="showServiceAreaInput">+ 添加区域</el-button>
                    </div>
                    <div class="json-preview">
                      <el-collapse>
                        <el-collapse-item title="JSON预览" name="service-area-preview">
                          <pre>{{ JSON.stringify(serviceAreasList, null, 2) }}</pre>
                        </el-collapse-item>
                      </el-collapse>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="配送方式" prop="deliveryMethods">
                  <div class="json-editor-container">
                    <div class="json-editor-header">
                      <span>配送方式配置</span>
                      <el-button size="mini" type="primary" icon="el-icon-plus" @click="addDeliveryMethod">添加方式</el-button>
                    </div>
                    <div class="features-list">
                      <el-tag
                        v-for="(method, index) in deliveryMethodsList"
                        :key="index"
                        closable
                        @close="removeDeliveryMethod(index)"
                        style="margin-right: 8px; margin-bottom: 8px;"
                        size="medium"
                        type="success"
                      >
                        {{ method }}
                      </el-tag>
                      <el-input
                        v-if="deliveryInputVisible"
                        v-model="deliveryInputValue"
                        ref="saveDeliveryInput"
                        size="small"
                        style="width: 120px;"
                        @keyup.enter.native="handleDeliveryInputConfirm"
                        @blur="handleDeliveryInputConfirm"
                      />
                      <el-button v-else size="small" @click="showDeliveryInput">+ 添加方式</el-button>
                    </div>
                    <div class="json-preview">
                      <el-collapse>
                        <el-collapse-item title="JSON预览" name="delivery-preview">
                          <pre>{{ JSON.stringify(deliveryMethodsList, null, 2) }}</pre>
                        </el-collapse-item>
                      </el-collapse>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结算周期(天)" prop="settlementCycle">
                  <el-input-number v-model="form.settlementCycle" :min="1" placeholder="结算周期" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="服务说明" prop="serviceDescription">
                  <el-input v-model="form.serviceDescription" type="textarea" :rows="3" placeholder="服务说明" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 财务评级 -->
          <el-tab-pane label="财务评级" name="finance">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="信用等级" prop="creditRating">
                  <el-select v-model="form.creditRating" placeholder="信用等级" style="width: 100%">
                    <el-option label="AAA" value="AAA" />
                    <el-option label="AA" value="AA" />
                    <el-option label="A" value="A" />
                    <el-option label="BBB" value="BBB" />
                    <el-option label="BB" value="BB" />
                    <el-option label="B" value="B" />
                    <el-option label="CCC" value="CCC" />
                    <el-option label="CC" value="CC" />
                    <el-option label="C" value="C" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="平均评分" prop="avgRating">
                  <el-input-number v-model="form.avgRating" :min="0" :max="5" :step="0.1" :precision="2" placeholder="平均评分" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="保证金余额(元)" prop="depositBalance">
                  <el-input-number v-model="form.depositBalance" :min="0" :precision="2" placeholder="保证金余额" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="佣金费率(%)" prop="commissionRate">
                  <el-input-number v-model="form.commissionRate" :min="0" :max="1" :step="0.001" :precision="4" placeholder="佣金费率" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="总订单数" prop="totalOrders">
                  <el-input-number v-model="form.totalOrders" :min="0" placeholder="总订单数" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="总产品数" prop="totalProducts">
                  <el-input-number v-model="form.totalProducts" :min="0" placeholder="总产品数" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 状态管理 -->
          <el-tab-pane label="状态管理" name="status">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="认证状态" prop="certificationStatus">
                  <el-select v-model="form.certificationStatus" placeholder="认证状态" style="width: 100%">
                    <el-option label="未认证" :value="0" />
                    <el-option label="已认证" :value="1" />
                    <el-option label="认证失败" :value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请状态" prop="applicationStatus">
                  <el-select v-model="form.applicationStatus" placeholder="申请状态" style="width: 100%">
                    <el-option label="待申请" :value="0" />
                    <el-option label="申请中" :value="1" />
                    <el-option label="申请通过" :value="2" />
                    <el-option label="申请拒绝" :value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="审核状态" prop="auditStatus">
                  <el-select v-model="form.auditStatus" placeholder="审核状态" style="width: 100%">
                    <el-option label="待审核" :value="0" />
                    <el-option label="审核通过" :value="1" />
                    <el-option label="审核拒绝" :value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="form.status" placeholder="状态" style="width: 100%">
                    <el-option label="待激活" :value="0" />
                    <el-option label="启用" :value="1" />
                    <el-option label="冻结" :value="2" />
                    <el-option label="注销" :value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="认证时间" prop="certificationTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.certificationTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="认证时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请时间" prop="applicationTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.applicationTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="申请时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="申请原因" prop="applicationReason">
                  <el-input v-model="form.applicationReason" type="textarea" :rows="3" placeholder="申请成为供应商的原因" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审核时间" prop="auditTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.auditTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="审核时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审核人" prop="auditor">
                  <el-input v-model="form.auditor" placeholder="审核人" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="审核备注" prop="auditRemark">
                  <el-input v-model="form.auditRemark" type="textarea" :rows="2" placeholder="审核备注" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSuppliers, getSuppliers, delSuppliers, addSuppliers, updateSuppliers } from "@/api/system/suppliers";
import { listUser } from "@/api/system/user";

export default {
  name: "Suppliers",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备供应商表格数据
      suppliersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前激活的标签页
      activeTab: 'basic',
      // 服务区域可视化编辑
      serviceAreasList: [],
      serviceAreaInputVisible: false,
      serviceAreaInputValue: '',
      // 配送方式可视化编辑
      deliveryMethodsList: [],
      deliveryInputVisible: false,
      deliveryInputValue: '',
      // 用户选择相关
      userOptions: [],
      userLoading: false,
      // 查询参数（精简版）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        supplierCode: null,
        supplierName: null,
        supplierType: null,
        certificationStatus: null,
        applicationStatus: null,
        auditStatus: null,
        status: null,
        contactPerson: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        supplierCode: [
          { required: true, message: "供应商编码不能为空", trigger: "blur" }
        ],
        supplierName: [
          { required: true, message: "供应商名称不能为空", trigger: "blur" }
        ],
        supplierType: [
          { required: true, message: "供应商类型：1-个人供应商，2-企业供应商，3-平台自营不能为空", trigger: "change" }
        ],
        certificationStatus: [
          { required: true, message: "认证状态：0-未认证，1-已认证，2-认证失败不能为空", trigger: "change" }
        ],
        applicationStatus: [
          { required: true, message: "申请状态：0-待申请，1-申请中，2-申请通过，3-申请拒绝不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态：0-待激活，1-启用，2-冻结，3-注销不能为空", trigger: "change" }
        ],
        auditStatus: [
          { required: true, message: "审核状态：0-待审核，1-审核通过，2-审核拒绝不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  computed: {
    // 简化的身份证照片对象
    simpleIdCardObject() {
      const obj = {};
      if (this.form.idCardFront) {
        obj.front = this.form.idCardFront;
      }
      if (this.form.idCardBack) {
        obj.back = this.form.idCardBack;
      }
      return obj;
    }
  },
  watch: {
    // 监听身份证正面图片变化
    'form.idCardFront': {
      handler(newVal, oldVal) {
        console.log('🔍 Watch监听到身份证正面图片变化:', oldVal, '->', newVal);
        if (newVal !== oldVal) {
          this.$nextTick(() => {
            this.updateSimpleIdCardForm();
          });
        }
      },
      immediate: false,
      deep: false
    },
    // 监听身份证背面图片变化
    'form.idCardBack': {
      handler(newVal, oldVal) {
        console.log('🔍 Watch监听到身份证背面图片变化:', oldVal, '->', newVal);
        if (newVal !== oldVal) {
          this.$nextTick(() => {
            this.updateSimpleIdCardForm();
          });
        }
      },
      immediate: false,
      deep: false
    }
  },
  created() {
    this.getList();
    this.loadInitialUsers();
  },
  methods: {
    /** 查询设备供应商列表 */
    getList() {
      this.loading = true;
      listSuppliers(this.queryParams).then(response => {
        this.suppliersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        supplierId: null,
        userId: null,
        supplierCode: null,
        supplierName: null,
        supplierType: null,
        contactPerson: null,
        contactPhone: null,
        contactEmail: null,
        contactAddress: null,
        companyName: null,
        businessLicense: null,
        taxNumber: null,
        legalPerson: null,
        certificationStatus: null,
        certificationTime: null,
        idCard: null,
        idCardImages: null,
        idCardFront: null,
        idCardBack: null,
        businessLicenseImage: null,
        serviceAreas: null,
        deliveryMethods: null,
        serviceDescription: null,
        creditRating: null,
        avgRating: null,
        totalOrders: null,
        totalProducts: null,
        depositBalance: null,
        commissionRate: null,
        settlementCycle: null,
        applicationReason: null,
        applicationTime: null,
        applicationStatus: null,
        status: null,
        auditStatus: null,
        auditRemark: null,
        auditTime: null,
        auditor: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.activeTab = 'basic';
      this.resetJsonEditors();
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.supplierId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备供应商";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const supplierId = row.supplierId || this.ids
      getSuppliers(supplierId).then(response => {
        this.form = response.data;
        // 初始化JSON编辑器
        this.initSimpleIdCardFromForm();
        this.initServiceAreasFromForm();
        this.initDeliveryMethodsFromForm();
        this.open = true;
        this.title = "修改设备供应商";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 提交前同步JSON数据
      console.log('🔍 提交表单前同步数据');
      this.updateSimpleIdCardForm();
      this.updateServiceAreasForm();
      this.updateDeliveryMethodsForm();
      
      console.log('🔍 最终提交的表单数据:');
      console.log('- idCardImages:', this.form.idCardImages);
      console.log('- serviceAreas:', this.form.serviceAreas);
      console.log('- deliveryMethods:', this.form.deliveryMethods);
      
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.supplierId != null) {
            updateSuppliers(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSuppliers(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const supplierIds = row.supplierId || this.ids;
      this.$modal.confirm('是否确认删除设备供应商编号为"' + supplierIds + '"的数据项？').then(function() {
        return delSuppliers(supplierIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/suppliers/export', {
        ...this.queryParams
      }, `suppliers_${new Date().getTime()}.xlsx`)
    },

    // ========== 状态显示辅助方法 ==========
    getSupplierTypeText(type) {
      const typeMap = { 1: '个人', 2: '企业', 3: '自营' }
      return typeMap[type] || '未知'
    },
    getSupplierTypeColor(type) {
      const colorMap = { 1: 'primary', 2: 'success', 3: 'warning' }
      return colorMap[type] || ''
    },
    getCertificationStatusText(status) {
      const statusMap = { 0: '未认证', 1: '已认证', 2: '认证失败' }
      return statusMap[status] || '未知'
    },
    getCertificationStatusColor(status) {
      const colorMap = { 0: 'info', 1: 'success', 2: 'danger' }
      return colorMap[status] || ''
    },
    getApplicationStatusText(status) {
      const statusMap = { 0: '待申请', 1: '申请中', 2: '申请通过', 3: '申请拒绝' }
      return statusMap[status] || '未知'
    },
    getApplicationStatusColor(status) {
      const colorMap = { 0: 'info', 1: 'warning', 2: 'success', 3: 'danger' }
      return colorMap[status] || ''
    },
    getAuditStatusText(status) {
      const statusMap = { 0: '待审核', 1: '已通过', 2: '已拒绝' }
      return statusMap[status] || '未知'
    },
    getAuditStatusColor(status) {
      const colorMap = { 0: 'warning', 1: 'success', 2: 'danger' }
      return colorMap[status] || ''
    },
    getStatusText(status) {
      const statusMap = { 0: '待激活', 1: '启用', 2: '冻结', 3: '注销' }
      return statusMap[status] || '未知'
    },
    getStatusColor(status) {
      const colorMap = { 0: 'info', 1: 'success', 2: 'warning', 3: 'danger' }
      return colorMap[status] || ''
    },
    getCreditRatingColor(rating) {
      const colorMap = {
        'AAA': 'success', 'AA': 'success', 'A': 'primary',
        'BBB': 'primary', 'BB': 'warning', 'B': 'warning',
        'CCC': 'danger', 'CC': 'danger', 'C': 'danger'
      }
      return colorMap[rating] || 'info'
    },

    // ========== 简化身份证照片管理方法 ==========
    // 身份证正面图片变化事件
    onIdCardFrontChange(newVal) {
      console.log('🔥 image-upload正面图片事件触发:', newVal);
      console.log('🔥 当前form.idCardFront值:', this.form.idCardFront);
      this.$nextTick(() => {
        console.log('🔥 nextTick后form.idCardFront值:', this.form.idCardFront);
        this.updateSimpleIdCardForm();
      });
    },
    
    // 身份证背面图片变化事件
    onIdCardBackChange(newVal) {
      console.log('🔥 image-upload背面图片事件触发:', newVal);
      console.log('🔥 当前form.idCardBack值:', this.form.idCardBack);
      this.$nextTick(() => {
        console.log('🔥 nextTick后form.idCardBack值:', this.form.idCardBack);
        this.updateSimpleIdCardForm();
      });
    },
    
    updateSimpleIdCardForm() {
      console.log('🔍 更新身份证照片JSON');
      console.log('正面图片URL:', this.form.idCardFront);
      console.log('正面图片URL类型:', typeof this.form.idCardFront);
      console.log('正面图片URL长度:', this.form.idCardFront ? this.form.idCardFront.length : 0);
      console.log('背面图片URL:', this.form.idCardBack);
      console.log('背面图片URL类型:', typeof this.form.idCardBack);
      
      // 直接在方法内构建对象，避免计算属性时机问题
      const idCardObj = {};
      
      // 更严格的判断条件
      const frontUrl = this.form.idCardFront;
      const backUrl = this.form.idCardBack;
      
      console.log('🔍 处理正面图片:', frontUrl);
      console.log('🔍 正面图片是否为字符串:', typeof frontUrl === 'string');
      console.log('🔍 正面图片是否有内容:', frontUrl && frontUrl.length > 0);
      
      if (frontUrl && typeof frontUrl === 'string' && frontUrl.trim() !== '') {
        idCardObj.front = frontUrl.trim();
        console.log('✅ 添加正面图片到JSON对象:', frontUrl.trim());
      } else {
        console.log('❌ 正面图片为空或无效，值为:', frontUrl);
      }
      
      console.log('🔍 处理背面图片:', backUrl);
      if (backUrl && typeof backUrl === 'string' && backUrl.trim() !== '') {
        idCardObj.back = backUrl.trim();
        console.log('✅ 添加背面图片到JSON对象:', backUrl.trim());
      } else {
        console.log('❌ 背面图片为空或无效，值为:', backUrl);
      }
      
      console.log('合成的JSON对象:', idCardObj);
      
      this.form.idCardImages = JSON.stringify(idCardObj);
      
      console.log('最终的JSON字符串:', this.form.idCardImages);
      
      // 强制更新视图
      this.$forceUpdate();
    },

    // ========== 服务区域可视化编辑方法 ==========
    addServiceArea() {
      this.showServiceAreaInput();
    },
    removeServiceArea(index) {
      this.serviceAreasList.splice(index, 1);
      this.updateServiceAreasForm();
    },
    showServiceAreaInput() {
      this.serviceAreaInputVisible = true;
      this.$nextTick(() => {
        if (this.$refs.saveServiceAreaInput) {
          this.$refs.saveServiceAreaInput.$refs.input.focus();
        }
      });
    },
    handleServiceAreaInputConfirm() {
      const inputValue = this.serviceAreaInputValue;
      if (inputValue && !this.serviceAreasList.includes(inputValue)) {
        this.serviceAreasList.push(inputValue);
      }
      this.serviceAreaInputVisible = false;
      this.serviceAreaInputValue = '';
      this.updateServiceAreasForm();
    },
    updateServiceAreasForm() {
      this.form.serviceAreas = JSON.stringify(this.serviceAreasList);
    },

    // ========== 配送方式可视化编辑方法 ==========
    addDeliveryMethod() {
      this.showDeliveryInput();
    },
    removeDeliveryMethod(index) {
      this.deliveryMethodsList.splice(index, 1);
      this.updateDeliveryMethodsForm();
    },
    showDeliveryInput() {
      this.deliveryInputVisible = true;
      this.$nextTick(() => {
        if (this.$refs.saveDeliveryInput) {
          this.$refs.saveDeliveryInput.$refs.input.focus();
        }
      });
    },
    handleDeliveryInputConfirm() {
      const inputValue = this.deliveryInputValue;
      if (inputValue && !this.deliveryMethodsList.includes(inputValue)) {
        this.deliveryMethodsList.push(inputValue);
      }
      this.deliveryInputVisible = false;
      this.deliveryInputValue = '';
      this.updateDeliveryMethodsForm();
    },
    updateDeliveryMethodsForm() {
      this.form.deliveryMethods = JSON.stringify(this.deliveryMethodsList);
    },

    // ========== 初始化JSON数据方法 ==========
    initSimpleIdCardFromForm() {
      try {
        console.log('🔍 初始化身份证照片，原始JSON:', this.form.idCardImages);
        
        if (this.form.idCardImages) {
          const images = JSON.parse(this.form.idCardImages);
          this.form.idCardFront = images.front || null;
          this.form.idCardBack = images.back || null;
          
          console.log('🔍 解析后的身份证照片:');
          console.log('- 正面:', this.form.idCardFront);
          console.log('- 背面:', this.form.idCardBack);
        } else {
          this.form.idCardFront = null;
          this.form.idCardBack = null;
          console.log('🔍 身份证照片JSON为空，设置为null');
        }
      } catch (e) {
        console.warn('❌ 身份证照片JSON解析失败:', e);
        this.form.idCardFront = null;
        this.form.idCardBack = null;
      }
    },
    initServiceAreasFromForm() {
      try {
        if (this.form.serviceAreas) {
          this.serviceAreasList = JSON.parse(this.form.serviceAreas);
        } else {
          this.serviceAreasList = [];
        }
      } catch (e) {
        console.warn('服务区域JSON解析失败:', e);
        this.serviceAreasList = [];
      }
    },
    initDeliveryMethodsFromForm() {
      try {
        if (this.form.deliveryMethods) {
          this.deliveryMethodsList = JSON.parse(this.form.deliveryMethods);
        } else {
          this.deliveryMethodsList = [];
        }
      } catch (e) {
        console.warn('配送方式JSON解析失败:', e);
        this.deliveryMethodsList = [];
      }
    },

    // 重置JSON编辑器
    resetJsonEditors() {
      this.serviceAreasList = [];
      this.serviceAreaInputVisible = false;
      this.serviceAreaInputValue = '';
      this.deliveryMethodsList = [];
      this.deliveryInputVisible = false;
      this.deliveryInputValue = '';
    },

    // ========== 用户选择相关方法 ==========
    /** 获取用户列表 */
    getUserList(query) {
      if (query !== '') {
        this.userLoading = true;
        listUser({
          pageNum: 1,
          pageSize: 20,
          userName: query,
          status: '0' // 只获取正常状态的用户
        }).then(response => {
          this.userOptions = response.rows || [];
          this.userLoading = false;
        }).catch(() => {
          this.userLoading = false;
        });
      } else {
        this.userOptions = [];
      }
    },

    /** 初始化时加载部分用户 */
    loadInitialUsers() {
      this.userLoading = true;
      listUser({
        pageNum: 1,
        pageSize: 10,
        status: '0'
      }).then(response => {
        this.userOptions = response.rows || [];
        this.userLoading = false;
      }).catch(() => {
        this.userLoading = false;
      });
    }
  }
};
</script>

<style scoped>
.json-editor-container {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  padding: 15px;
  background-color: #FAFAFA;
}

.json-editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #E4E7ED;
}

.json-editor-header span {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.id-card-simple-layout {
  margin-bottom: 15px;
}

.id-card-item {
  text-align: center;
  padding: 15px;
  background-color: #FFFFFF;
  border: 1px solid #E4E7ED;
  border-radius: 6px;
}

.id-card-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
  font-size: 14px;
}

.image-item {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #FFFFFF;
  border: 1px solid #E4E7ED;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.image-item:last-child {
  margin-bottom: 0;
}

.image-preview-container {
  display: flex;
  align-items: flex-start;
  gap: 15px;
}

.image-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.image-type-tag {
  background-color: #E1F5FE;
  color: #0277BD;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  display: inline-block;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #fafafa;
  color: #909399;
}

.image-slot .el-icon-picture-outline {
  font-size: 30px;
}

.features-list {
  min-height: 60px;
  padding: 10px;
  background-color: #FFFFFF;
  border: 1px solid #E4E7ED;
  border-radius: 4px;
  margin-bottom: 15px;
}

.json-preview {
  margin-top: 15px;
}

.json-preview pre {
  background-color: #F5F7FA;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  max-height: 200px;
  overflow-y: auto;
}

.el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .json-editor-container {
    padding: 10px;
  }
  
  .image-item {
    padding: 8px;
  }
}
</style>
